import { Directive, forwardRef, Input } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator } from '@angular/forms';

import { NumberRules } from './interface';

/**
 * 数值验证
 */
@Directive({
  selector: '[NumberValidator]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(() => NumberValidatorDirective),
      multi: true
    }
  ]
})
export class NumberValidatorDirective implements Validator {
  @Input() rules: NumberRules = {
    max: 2000,
    min: -2000,
    float: 2,
    item: 'DS'
  };

  validate(c: AbstractControl): { [key: string]: any } | null {
    const v = c.value;
    if (v === null) {
      return null;
    }
    if (v > this.rules.max) {
      const msg = `${this.rules.item}数值过大，建议在${this.rules.min}~${this.rules.max}以内`;
      this.sendErrorMsgToForm('ValidatorMsg', msg);
      return { ValidatorMsg: msg };
    }
    if (v < this.rules.min) {
      const msg = `${this.rules.item}数值过小，建议在${this.rules.min}~${this.rules.max}以内`;
      this.sendErrorMsgToForm('ValidatorMsg', msg);
      return { ValidatorMsg: msg };
    }

    const y = String(v).indexOf('.') + 1; // 获取小数点的位置
    const count = String(v).length - y; // 获取小数点后的个数
    if (y > 0) {
      if (count > this.rules.float) {
        const msg = `${this.rules.item}小数部分过长，建议在${this.rules.float}以内`;
        this.sendErrorMsgToForm('ValidatorMsg', msg);
        return { ValidatorMsg: msg };
      }
    }

    return null;
  }

  /**
   * 错误信息推送
   * @Parmas: key  [发送数据的唯一标识]
   * @Parmas: res  [需要发送的数据源]
   */
  sendErrorMsgToForm(key: string, res: any): void {
    // TODO: 错误信息发布
  }
}
